﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using MUM.Models;
using MarketPulse.BusinessLogic.Core.Security;
using MarketPulse.Web.Helpers;

namespace MUM.Controllers
{
    public class SecurityController : MarketPulse.Web.Mvc.Controller
    {
        //
        // GET: /login/

        public virtual ActionResult GetView()
        {
            return View();
        }

        public ActionResult RedirectAuthentication()
        {
            bool isAuthenticated = SessionManager.Authenticated;
            if (!isAuthenticated)
            {
                return RedirectToAction("GetView", "Security");
            }

            return RedirectToAction(SessionManager.ActiveAction, SessionManager.ActiveController);
        }

        [HttpPost]
        public ActionResult GetView(SecurityModel model)
        {
            if (ModelState.IsValid)
            {
                //Login User by Verifying Username and Password.
                if (IsLoggedIn(model.Username.Trim(), model.Password.Trim()))
                {
                    //FormsAuthentication.SetAuthCookie(model.Username, true);

                    // If the user was redirected from another page to the login screen, take them back.
                    if (!String.IsNullOrEmpty(SessionManager.LastUrl))
                    {
                        var lastUrl = SessionManager.LastUrl;
                        SessionManager.LastUrl = String.Empty;
                        return RedirectToAction(lastUrl);
                    }
                    else
                    {
                        return RedirectToAction("index", "home");
                        //SessionManager.ApplicationProfile.HomeScreen
                    }
                    
                }
                {
                    ModelState.AddModelError("", "Invalid username or password");
                }
               
            }

            return View();
        }

        /// <summary>
        /// Method used to authenticate the user
        /// </summary>
        /// <param name="userName">The username to use</param>
        /// <param name="password">the password to use</param>
        private bool IsLoggedIn(string userName, string password)
        {
            bool isLoggedIn = false;
            //Login User by Verifying Username and Password.
            try
            {
                //pnlMessage.Visible = false;

                string ipAddress = Request.UserHostAddress.ToString();
                Guid profileTypeGuid = Guid.Parse(ConfigurationManager.AppSettings["ProfileTypeGUID"].ToString());

                SessionManager.ApplicationProfile = MarketPulseSecurity.Login(userName, password, ipAddress, profileTypeGuid);

                // Profile is set to null if the login failed but didn't throw an exception.
                if (SessionManager.Authenticated == false)
                {
                    //lblMessage.Text = "Login Failed";
                    //pnlMessage.Visible = true;
                    isLoggedIn = false;
                }
                else
                {
                    isLoggedIn = true;
                }
            }
            catch (Exception ex)
            {
                //TODO setup some kind of exception handling   
                //mLog.Error("Exception thrown on login attempt by [ " + userName + " ] ", ex);
                //lblMessage.Text = "An error occured whilst attempting to log in";
                //pnlMessage.Visible = true;
                return false;
            }
            return isLoggedIn;
        }
        
    }
}
